package com.fatgirl.utils
{
	import flash.display.BlendMode;
	import flash.display.DisplayObject;
	import flash.display.MovieClip;
	import flash.display.Shape;
	import flash.display.Sprite;
	import flash.geom.ColorTransform;
	import flash.geom.Matrix;
	import flash.utils.Dictionary;


		/**
		 *  
		 * 对象池
		 * 用于一些重复频繁使用的对象
		 * 减少new过程的消耗
		 * @author iceman
		 * 
		 */
		public class ObjectPool 
		{
			
			private static var classInstances:Dictionary = new Dictionary(false)

			/**
			 * 获取对象 
			 * @param c
			 * @return 
			 * 
			 */
			public static function getInstanceOf(c:Class):Object 
			{
				
				if(!ObjectPool.classInstances[c])
				{
					ObjectPool.classInstances[c] = new Array;	
				}
				var instances:Array = ObjectPool.classInstances[c];
				
				if(instances.length==0) 
				{
					instances.push(new c());
				}
				
				var r:Object = instances.pop();
				if(r is MovieClip)
				{
					(r as MovieClip).gotoAndPlay(1);	
				}
				return r;

			}
			
			/**
			 * 归还对象 
			 * @param object
			 * 
			 */
			public static function returnInstance(object:Object):void 
			{

				if(!object) return;
				var c:Class = object.constructor;
				
				// 重置一些显示对象
				if(object is MovieClip) 
				{
					var m:MovieClip = object as MovieClip;
					m.gotoAndStop(1);
				}

				if(object is Sprite) 
				{
					var s:Sprite = object as Sprite;
					s.graphics.clear();
				}

				if(object is Shape) 
				{
					var sh:Shape = object as Shape;
					sh.graphics.clear();
				}

				if(object is DisplayObject) 
				{
					
					var d:DisplayObject = object as DisplayObject;
					d.x = 0;
					d.y = 0;
					d.alpha = 1;
					d.blendMode = BlendMode.NORMAL;
					d.cacheAsBitmap = false;
					d.filters = [];
					d.mask = null;
					d.rotation = 0;
					d.scaleX = 1;
					d.scaleY = 1;
					d.scrollRect = null;
					d.visible = true;
					d.transform.matrix = new Matrix();
					d.transform.colorTransform = new ColorTransform();
					
				}

				if(!ObjectPool.classInstances[c])
				{
					ObjectPool.classInstances[c] = new Array;	
				}
				var instances:Array = ObjectPool.classInstances[c];
				instances.push(object);

			}


			/**
			 * 释放对象池内存 
			 * @param c 若不为null时  仅仅释放这一种类的对象池，若为null全部对象池均会被回收
			 * 
			 */
			public static function flush(c:Class=null):void 
			{
				
				if(c!=null)
				{
					ObjectPool.classInstances[c] = null;	
				}
				else 
				{
					for(var i:* in ObjectPool.classInstances)
					{
						ObjectPool.classInstances[i] = null;
					}
				}
				//调用强制GC				
				GC.clear();

			}

			
		}

}